package com.atbun.eduservice.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description :树形结构数据
 * 注意：不管有多少节点，多少子节点，都可以使用
 * @Author : mayp
 * @Date: 2020-05-06 10:08
 */
@Data
public class TreeNode {

    //前端需要的属性
    private String id;
    private String parentId;
    private String title;

    private Date gmtCreate;
    private Date gmtModified;


//    child节点 --如果节点为空，就把空节点去掉
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    List<TreeNode> children = new ArrayList<>();

    public TreeNode(String id,String parentId,String title,Date gmtCreate,Date gmtModified){
        this.id = id;
        this.parentId = parentId;
        this.title = title;
        this.gmtCreate = gmtCreate;
        this.gmtModified = gmtModified;
    }

    /**
     * 使用静态内部类构造children结构
     */
    public static class  TreeNodeBuilder{
        public static List<TreeNode> build(List<TreeNode> treeNodes,String pid){
//            创建nodes存放children节点内容
            List<TreeNode> nodes = new ArrayList<>();
            for (TreeNode t1 : treeNodes){
//                判断当前节点的父id是否与根节点的id相同
                if (t1.getParentId().equals(pid)){
                    nodes.add(t1);
                }
                for (TreeNode t2 : treeNodes){
//                    内层循环会遍历每一个子节点，该子节点的父节点是否与外层循环的节点相同，如果相同，该子节点属于该父节点
                    if (t2.getParentId().equals(t1.getId())){
                        t1.getChildren().add(t2);
                    }
                }
            }
            return nodes;
        }
    }

}
